<?php

class XPathHelper
{
    public $xpath;
    public $curNode;
    
    public function __construct( DOMDocument $doc )
    {
        $this->xpath = new DOMXPath( $doc );
    }

    public function GetNodes( $expr, $node = null )
    {
        if ( is_null($node) )
        {
            $node = $this->curNode;
        }

        if ( is_null($node) )
        {
            $entries = $this->xpath->query( $expr );
        }
        else
        {
            $entries = $this->xpath->query( $expr, $node );
        }

        $nodeList = array();
        for ( $i = 0; $i < $entries->length; $i++ )
        {
            $nodeList[] = $entries->item($i);
        }
        return $nodeList;
    }

    public function GetNode( $expr, $node = null )
    {
        $nodes = $this->GetNodes( $expr, $node );
        $node = empty($nodes) ? null : $nodes[0];
        return $node;
    }

    public function Evaluate( $expr, $node = null )
    {
        if ( is_null($node) )
        {
            $node = $this->curNode;
        }

        if ( is_null($node) )
        {
            $result = $this->xpath->evaluate( $expr );
        }
        else
        {
            $result = $this->xpath->evaluate( $expr, $node );
        }
        return $result;
    }
    
    public function GetText( $expr = "", $node = null )
    {
        $expr = empty($expr) ? "text()" : "$expr/text()";
        $node = $this->GetNode( $expr, $node );
        return is_null($node) ? null : $node->nodeValue;
    }
    
    public function NodeExists( $expr, $node = null )
    {
        return !is_null($this->GetNode($expr, $node));
    }
}

?>
